<template>
  <el-dialog title="修改密码" width="650" v-model="visible" @close="handleCloseDialog">
    <UtilForm :labels="formLabels" :data="state.form" @emit-util-form="echoUtilFormHanler">
      <el-row>
        <el-text type="warning">注意：请妥善保管新密码，系统将在密码修改成功 3 秒后登出</el-text>
      </el-row>
      <el-row>
        <el-button @click="handleCloseDialog">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确认</el-button>
      </el-row>
    </UtilForm>
  </el-dialog>
</template>

<script setup>
import UtilForm from '../../components/UtilForm.vue';
import { encryptAES } from '../../utils/aes';
import { reactive, ref, watch, getCurrentInstance } from 'vue';
import { useStore } from 'vuex';
import { ElMessage } from 'element-plus';

const store = useStore();
const { proxy: { $axios } } = getCurrentInstance();
const emit = defineEmits(['emit-status']);
const props = defineProps({
  status: Boolean
});

const storeUser = store.getters['user/getUser'];
const visible = ref(false);
const formLabels = reactive([
  { field: 'password', label: '原密码', labelType: 'password', disabled: false, required: true, showPassword: true },
  { field: 'newPassword', label: '新密码', labelType: 'password', disabled: false, required: true, showPassword: true },
  { field: 'confirmPassword', label: '确认密码', labelType: 'password', disabled: false, required: true, showPassword: true },
]);
const state = reactive({
  form: {}
});

watch(() => props.status, value => {
  visible.value = value
});

async function handleSubmit() {
  const path = '/api/auth/changePassword/' + storeUser.id;
  const reqParams = setReqParams();

  try {
    const { code, message } = await $axios.post(path, reqParams);

    if (code === 200) {
      ElMessage.success(message + '，请重新登录');
      handleCloseDialog()
    }
  } catch (error) {
    console.log('密码修改失败', error);
  }
}

function setReqParams(labels = formLabels) {
  const params = {
    username: storeUser.username
  };
  labels.forEach(({ field }) => params[field] = encryptAES(state.form[field]));
  return params
}

function handleCloseDialog() {
  visible.value = false;
  emit('emit-status', { status: false });
}

function echoUtilFormHanler(data) {
  state.form = data.form;
}
</script>

<style scoped>
.custom-label {
  width: 120px;
  text-align: right;
}

:deep(.el-descriptions__cell) {
  display: flex;
}

/* :deep(tr:last-child .el-descriptions__cell) {
  display: flex;
  padding-left: 120px;
} */
</style>